Lists

A list is a collection which is ordered and changeable. 
  • In Python lists is container which hold comma-sperated values are written within square brackets. we can define a list as an object that contains multiple data items (elements). 
  • The contents of a list can be changed during program execution. The size of a list can also change during execution, as elements are added or removed from it.
Create List
To build a list, just put some expressions in square brackets. The syntax is:

lst1 = [ ]  # lst1 is the name of the list
lst2 = [expression1 , …. , expression_N]

list = [3, 22, 30, 5.3, 20]
  • The first value in the list above, 3, has an index of 0
  • The second value, 22, has an index of 1
  • The third value, 30, has an index of 2
  • The fourth value, 5.3, has an index of 3 and so on
  • The last member of a list can also be accessed by using the index -1. For example,print(list[-1]) 20
  • The 2nd las number can be accessed by using the index -2 and so on ..
lst=[1,2,3,4,5,6,7,8,9,10]
print(lst)

#print the first element of List
print(lst[0])

#print the last element of List
print(lst[-1])

#print the first 3rd element of List
print(lst[:3])

#print the elemnts between a give range
print(lst[2:6])
 
Python lists can be homogeneous, meaning that they can contain the same type of objects; or heterogeneous, including different types of objects.

Homogeneous List
#String List
fruits = ["apple", "banana", "cherry","greps","papaya"]
print(fruits)
['apple', 'banana', 'cherry', 'greps', 'papaya']
# Integer List
num=[1,2,3,4,5,6]
print(num)
[1, 2, 3, 4, 5, 6]
# floating List
numbers = [2.2, 4.5, 9.8, 10.4]
print(numbers)
[2.2, 4.5, 9.8, 10.4]
 
Heterogeneous List
# Mixed List
emp=["Jhon","CA",101,"CS"]
print(emp)
['Jhon', 'CA', 101, 'CS']
 
Empty List
empty_List=[]
# Empty List
empty=[]
print(empty)
[]

Accessing the List Items
List items can be accessed by refering to index number
fruits = ["apple", "banana", "cherry","greps","papaya"]
print(fruits[1])
banana
Negative Indexing
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc.
fruits = ["apple", "banana", "cherry","greps","papaya"]
print(fruits[-1])
papaya
 
Range of Indexes
You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]

print(fruits[2:5])
print(fruits[:5])


print(fruits[2:])


Update the value in the List
List is mutable in nature i.e. after creating list you can change the value of the list. To change the value of specific item refer to index number
fruits = ["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
fruits

fruits[1] = "blackcurrant"
fruits

fruits = ["apple","banana","cherry","greps","papaya","orange"]
fruits.append("greaps")


Remove an elements from List
There are three ways in which you can Remove elements from List:
  1. Using the remove() method
  2. Using the list object’s pop() method
  3. Using the del operator

List Object's remove() method:

The remove() method is one of the most commonly used list object methods to remove an item or an element from the list. When you use this method, you will need to specify the particular item that is to be removed.

  • Note that, if there are multiple occurrences of the item specified, then its first occurrence will be removed from the list. 
  • If the particular item to be removed is not found, then a ValueError is raised.
fruits = ["apple","banana","cherry","greps","papaya","orange"]
fruits.remove("banana")
print(fruits)

List Object's remove() method:

The pop() method is another commonly used list object method. This method removes an item or an element from the list, and returns it. The difference between this method and the remove() method is that, we should specify the item to be removed in the remove() method. But, when using the pop(), we specify the index of the item as the argument, and hence, it pops out the item to be returned at the specified index. If the particular item to be removed is not found, then an IndexError is raised.

fruits = ["apple","banana","cherry","greps","papaya","orange"]
fruits.pop(2)
print(fruits)

Python del operators:

This operator is similar to the List object’s pop() method with one important difference. The del operator removes the item or an element at the specified index location from the list, but the removed item is not returned, as it is with the pop() method. So essentially, this operator takes the item’s index to be removed as the argument and deletes the item at that index. The operator also supports removing a range of items in the list. Please note, this operator, just like the pop() method, raises an IndexError, when the index or the indices specified are out of range.

The syntax for deleting an element from a list is:
del list_name[index_val];

The count() is a built-in function in Python. It will return you the count of a given element in the list.

Syntax:
list.count(element)
element: The element you want to find the count.

list = ['red', 'green', 'blue', 'orange', 'green', 'gray', 'green']
color_count = list.count('green')
print('The count of color: green is ', color_count)

Print List item one by one
lst=[1,2,3,4,5,6,7,8,9,10]
for x in lst:
print(x)
To determine if a specified item is present in a list use the in keyword
check if apple is persent in the list
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits
  print("Yes apple is in the fruits list")

Remove duplicates from the List
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']

unique = list(set(items))

Find the duplicates counts from the List
items = [1, 2, 3, 'a', 'b', 'c', 2, 3, 4, 'b', 'c', 'd']
unique = items.count(3)


Extend a list
Extends the list by appending all elements from an iterable, like adding more ingredients to your recipe from another recipe.
fruits = ["apple","banana","cherry","greps","papaya","orange"]
more_fruits = ["pineapple","watemelon"]
fruits.extend(more_fruits)
print(fruits)

Check the element in the list
is_apple_present = "apple" in fruits
print(is_apple_present)

Python List index() 
The index() method returns the index of the specified element in the list.
list.index(element, start, end)
# vowels list
vowels = ['a', 'e', 'i', 'o', 'i', 'u']
# index of 'e' in vowels
index = vowels.index('e')
print('The index of e:', index)
# element 'i' is searched
# index of the first 'i' is returned
index = vowels.index('i')
print('The index of i:', index)
Append the List Items
# animals list
animals = ['cat', 'dog', 'rabbit']
# Animals list
print('animals list')
print(animals)
# 'guinea pig' is appended to the animals list
animals.append('guinea pig')
# Updated animals list
print('Updated animals list:',animals)


Nested List

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


Access the nested List elements
print(nested_list[1][1])  
# Output: 5









No comments:

Post a Comment